<?php
/* --------------------------------------------------------------
   create_rfm_thumbnails.php 2023-02-13
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2023 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

declare(strict_types=1);

/**
 * Sends an HTTP-response with the smallest GIF as possible (26 bytes white 1x1 pixel gif).
 */
#[NoReturn]
function responseSmallestGIF(): void
{
    sendNoCacheHeaders();
    header('Content-Type: image/gif');
    echo base64_decode('R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=');
    exit;
}

function sendNoCacheHeaders(): void
{
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
}

function fix_strtolower($str): string
{
    if (function_exists('mb_strtolower')) {
        return mb_strtolower($str);
    }

    return strtolower($str);
}

const ALLOWED_IMAGE_EXTENSIONS = [
    'jpeg',
    'jpg',
    'png',
    'gif',
    'webp',
];

ini_set('display_errors', '1');

require_once __DIR__ . '/include/php_image_magician.php';

$requestUri = $_SERVER['REQUEST_URI'] ?? null;
if ($requestUri === null) {
    responseSmallestGIF();
}
$requestUriSegments = explode('/', $requestUri);

// get filename and extension for further processing
$imageFile         = array_pop($requestUriSegments);
$imageFileSegments = explode('.', $imageFile);
$fileExtension     = array_pop($imageFileSegments);

if (!in_array(strtolower($fileExtension), ALLOWED_IMAGE_EXTENSIONS, true)) {
    responseSmallestGIF();
}

// get subdirectory path after 'ResponsiveFilemanager/thumbs' directory
$rfmDirectoryName  = 'ResponsiveFilemanager';
$rfmDirectoryIndex = array_search($rfmDirectoryName, $requestUriSegments, true);
if ($rfmDirectoryIndex === false) {
    responseSmallestGIF();
}

$length               = count($requestUriSegments);
$subDirectorySegments = [];

// we start from the rfm directory index + 2 in order to skip the 'ResponsiveFilemanager' and 'thumbs' directory
// only the subpath after 'ResponsiveFilemanager/thumbs' remains
for ($i = $rfmDirectoryIndex + 2; $i < $length; $i++) {
    $subDirectorySegments[] = $requestUriSegments[$i];
}
$subDirectory = implode('/', $subDirectorySegments);

$sourcePath         = dirname(__DIR__, 2) . "/$subDirectory";
$destinationPath    = dirname(__DIR__) . "/thumbs/$subDirectory";
$processedImagePath = "$destinationPath/$imageFile";

$imgFile = "$sourcePath/$imageFile";

try {
    $magicianObj = new \imageLib($imgFile);
    $magicianObj->resizeImage(122, 91, 'crop');
    $magicianObj->saveImage($processedImagePath, 80);
} catch (\Exception $e) {
    return $e->getMessage();
}

$processedImageContents = file_get_contents($processedImagePath);

sendNoCacheHeaders();
header("Content-Type: image/$fileExtension");
echo $processedImageContents;
